﻿using System.IO;
using System.Linq;
using Kotonoha.Objects;
using Kotonoha.Objects.SuperMemo;
using Kotonoha.Server.Core.Utils;
using NHibernate;


namespace Kotonoha.Server.Objects.Model.Event {
    public class MarkEvent : Event {

        public long WordId { get; set; }
        public int Mark { get; set; }
        public double ThinkSpan { get; set; }

        protected override void serializeInner(TextWriter writer) {
            writer.Write(WordId);
            writer.Write(";");
            writer.Write(Mark);
            writer.Write(";");
            writer.Write(ThinkSpan);
        }

        protected override void deserializeInner(TextReader reader) {
            string line = reader.ReadLine();
            string[] split = line.Split(';');
            WordId = long.Parse(split[0]);
            Mark = int.Parse(split[1]);
            ThinkSpan = double.Parse(split[2]);
        }

        public bool Equals(MarkEvent obj) {
            if (ReferenceEquals(null, obj)) {
                return false;
            }
            if (ReferenceEquals(this, obj)) {
                return true;
            }
            return base.Equals(obj) && obj.WordId == WordId && obj.Mark == Mark;
        }

        public override bool Equals(object obj) {
            if (ReferenceEquals(null, obj)) {
                return false;
            }
            if (ReferenceEquals(this, obj)) {
                return true;
            }
            return Equals(obj as MarkEvent);
        }

        public override int GetHashCode() {
            unchecked {
                int result = base.GetHashCode();
                result = (result * 397) ^ WordId.GetHashCode();
                result = (result * 397) ^ Mark;
                return result;
            }
        }

        public override void apply(Word word) {
            OFMatrixHolder.Matrix.Update(word.LearningData, Mark, Time);
        }

        public override void apply(WordHolder holder) {
            ISession session = HibernateUtil.Model.Session;
            Word w = holder[WordId];
            if (w.LearningData == null) {
                w.LearningData = new ItemLearningData();
                session.Save(w.LearningData);
            }
            apply(w);
            holder.Update(false, w);
        }
    }
}
